package com.thingple.util;

import java.util.Formatter;
import java.util.UUID;

public class Bytes {

    /**
     * default lowercase
     */
    public static boolean charsetUpperCase = false;

    /**
     * 0x11:0x2A:0x3F.....
     */
    public static String ByteToHexString(byte[] b) {
        int len = b.length;
        StringBuilder sb = new StringBuilder(b.length * (2 + 1));
        Formatter formatter = new Formatter(sb);

        for (int i = 0; i < len; i++) {
            if (i < len - 1)
                formatter.format("0x%02X:", b[i]);
            else
                formatter.format("0x%02X", b[i]);

        }
        formatter.close();

        return sb.toString();
    }

    public static boolean matchUuid(UUID uuid, String shortName) {

        return uuid.toString().split("-")[0].toUpperCase().endsWith(shortName);
    }

    /**
     * hex转byte数组
     * @param hex
     * @return
     */
    public static byte[] hexToByte(String hex) {
        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = Byte.valueOf((byte)intVal);
        }
        return ret;
    }

    /**
     * byte数组转hex
     * 0x110x2A0x3F.....
     */
    public static String byteToHex(byte[] bytes){
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        String s;
        if (charsetUpperCase) {
            s = sb.toString().trim().toUpperCase();
        } else {
            s = sb.toString().trim().toLowerCase();
        }
        return s;
    }

    public static String byteToHex(byte b){
        String s = Integer.toHexString(b & 0xFF);
        s = ((s.length() == 1) ? "0" + s : s); // 每个字节由两个字符表示，位数不够，高位
        if (charsetUpperCase) {
            s = s.trim().toUpperCase();
        } else {
            s = s.trim().toLowerCase();
        }
        return s;
    }
}
